import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// SharedPreferences存储
/// 1. 添加依赖
/// 2. 保存数据
/// 3. 读取数据
/// 4. 移除数据

class SharedPreferencesApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final String appTitle = 'SharedPreferences Demo';
    return MaterialApp(
      title: appTitle,
      theme: ThemeData(primarySwatch: Colors.red),
      home: SharedPreferencesAppPage(title: appTitle),
    );
  }
}

class SharedPreferencesAppPage extends StatefulWidget {
  final String title;

  SharedPreferencesAppPage({Key key, this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() => SharedPreferencesAppPageState();
}

class SharedPreferencesAppPageState extends State<SharedPreferencesAppPage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    _loadCounter();
  }

  _loadCounter() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    setState(() {
      _counter = (preferences.getInt('counter') ?? 0);
    });
  }

  _incrementCounter() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    setState(() {
      _counter = (preferences.getInt('counter') ?? 0) + 1;
      preferences.setInt('counter', _counter);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times.'),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
